package guoanmaker.personal.business.service;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
/**
 * 
* @ClassName: PersonalPicCodeService 
* @Description: 图片验证码service
* @author Yvonne_MGL
* @date 2017年9月12日 上午11:23:58 
*  
 */

import guoanmaker.personal.business.dao.PersonalUserDao;
import guoanmaker.personal.business.model.PersonalPicCode;
import guoanmaker.personal.business.model.ReturnResult;
import guoanmaker.personal.business.repository.PersonalPicCodeRepository;
import guoanmaker.personal.helper.common.util.ValidateCodeHelper;
@Service
public class PersonalPicCodeService {
	
	@Resource
	private PersonalPicCodeRepository PersonalPicCodeRepository;
	
	@Resource
	private PersonalUserDao personalUserDao;
	
	@Resource
	private PersonalCodeService personalCodeService;
	
	/**
	 * 
	* @Description: 生成图片验证码 
	* @param response
	* @param @return
	* @param @throws Exception
	* @author Yvonne_MGL 
	* @date 2017年9月12日 下午2:01:02     
	* @return PersonalPicCode    
	* @throws 
	 */
	@Transactional
	public PersonalPicCode getPicCode() throws Exception{
	    /*response.setContentType("image/jpeg");  
	    response.setHeader("Pragma", "no-cache");  
	    response.setHeader("Cache-Control", "no-cache");  
	    response.setDateHeader("Expires", 0);  */
	    ValidateCodeHelper vCode = new ValidateCodeHelper(120,40,5,100);  
	    //vCode.write(response.getOutputStream());  
	    PersonalPicCode picCode=new PersonalPicCode();
	    picCode.setCode(vCode.getCode());
	    picCode.setCreateTime(new Date());
	    PersonalPicCodeRepository.save(picCode);
	    return picCode;
	}
	
	/**
	 * 
	* @Description: 验证图片验证码，验证成功发送短信验证码 
	* @param id 图片验证码id
	* @param code 用户输入的图片验证码
	* @param telephone 电话号码
	* @param @return
	* @param @throws Exception
	* @author Yvonne_MGL 
	* @date 2017年9月12日 下午2:33:43     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult verifyPicCode(String id,String code,String telephone)throws Exception{
		ReturnResult returnResult=new ReturnResult();
		PersonalPicCode picCode=PersonalPicCodeRepository.findOne(id);
		if(picCode==null||!StringUtils.equalsIgnoreCase(code, picCode.getCode())){
			returnResult.setKey("error");
    		returnResult.setValue("验证码不正确");
		}else{
			picCode.setTelephone(telephone);
			PersonalPicCodeRepository.save(picCode);
			Long dayCodes=personalUserDao.getDayCodes(telephone);
			if(dayCodes>10){
				returnResult.setKey("error");
	    		returnResult.setValue("当天发送短信验证码次数过多");
			}else{
				returnResult=personalCodeService.sendCode(telephone);
			}
		}
		return returnResult;
	}

}
